package com.cml.domain.service;

import com.cml.application.ServerNodeApplication;
import com.cml.common.config.Configuration;
import com.cml.common.context.ServerContext;
import com.cml.domain.entity.ServerNode;
import com.cml.infrastructure.NetworkManager;
import org.apache.log4j.Logger;

import java.util.Collection;
import java.util.Map;

/**
 * 姓名：陈茂林
 * 时间：2023/11/8 8:18
 * 描述：
 */
public class ServerNodeManagerService {
    private NetworkManager networkManager;
    private ServerNode serverNode;

    private Configuration configuration;

    Logger logger = Logger.getLogger(ServerNodeManagerService.class);
    public ServerNodeManagerService(ServerContext serverContext){
        this.networkManager = serverContext.getNetworkManager();
        this.serverNode = serverContext.getServerNode();
        configuration = serverContext.getConfiguration();
    }

    public void start(){
        //启动网络接听
        this.networkManager.startNetworkConnectionListener();
        logger.info("网络端口启动完成");
        /**
         * 1)建立所有节点连接
         *   follower 连接所有节点
         *   observer 连接所有follower
         */
        this.connAllServerNode();

        /**
         * 选举
         */
        this.leaderElect();
    }

    public Integer leaderElect(){
        Integer leader=null;
        //只有follower才进行选举
        if(this.configuration.isFollower()){
            LeaderVoteService leaderVoteService = new LeaderVoteService(this.networkManager);
            leader= leaderVoteService.leaderElect();
            if(this.serverNode.getId().equals(leader)){
                this.serverNode.setLeader(true);
            }
        }
        //设置所有的连接对象，leader状态
        Map<Integer, ServerNode>  allRemoteServerNode=this.networkManager.getAllRemoteServerNode();
        Collection<ServerNode> serverNodeCollection =allRemoteServerNode.values();
        final Integer  leaderFinal=leader;
        serverNodeCollection.forEach(serverNode ->{
            if(serverNode.getId().equals(leaderFinal)){
                serverNode.setLeader(true);
            }
        });
        return leader;
    }

    private  void connAllServerNode(){
        if(this.configuration.isFollower()){
            this.networkManager.connOtherFollowerServerNode();
            logger.info("等待所有follower连接完成");
            this.networkManager.waitFollowerServerNodeConn();
            logger.info("等待所有节点连接完成");
            this.networkManager.waitAllServerNodeConn();
            logger.info("所有连接节点完成");
        }else{
            this.networkManager.connAllFollowerServerNode();
            logger.info("所有连接节点完成");
        }
    }
}
